<?php if(!defined('PUBLIC_DIR')) die('No Acces!');

Cnamespace('System');
class SQLite3DB implements iBaseDB {

	private $_link;
	private $_theQuery;
	private $_result;
	
	private $_array = null;

	public function __construct($connection, $new = false){
		$pathinfo = pathinfo($connection);
		if($new && is_file($connection))
			unlink($connection);
		if(is_dir($pathinfo['dirname']) === false)
			trigger_error('Katalog '.$pathinfo['dirname'].' nie istnieje!', E_USER_ERROR);
		if(is_file($connection) === false){
			if(is_writable($pathinfo['dirname']) === false)
				trigger_error('Zapis w katalogu '.$pathinfo['dirname'].' jest niemożliwy!', E_USER_ERROR);
			if(!$new) trigger_error('Plik '.$connection.' nie istnieje. Zostanie stworzona czysta baza.', E_USER_NOTICE);
		}else if(is_readable($connection) === false)
			trigger_error('Odczyt pliku '.$connection.' jest niemożliwy!', E_USER_ERROR);
		else if(is_writable($connection) === false)
			trigger_error('Zapis do pliku '.$connection.' jest niemożliwy!', E_USER_ERROR);
		$this->_link = new SQLite3($connection, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
		if($this->_link === false)
			trigger_error($this->_link->lastErrorMsg(), E_USER_ERROR);
	}

	public function Query($query){
		$this->_theQuery = $query;
		return $this->_result = $this->_link->query($this->_theQuery);
	}

	public function GetQuery(){
		return $this->_theQuery;
	}

	public function GetResult(){
		return $this->_result;
	}

	public function NumFields($result = null){
		if($result !== null)
			return $result->numColumns();
		else
			return $this->_result->numColumns();
	}

	public function NumRows($result = null){
		if($result !== null){
			$arr = array();
			$result->reset();
			while(false !== ($res = $this->FetchRow($result))){
				$arr[] = $res;
			}
			$result->reset();
			return count($arr);
		}else
			if($this->_array === null){
				$arr = array();
				$this->_result->reset();
				while(false !== ($res = $this->FetchRow($this->_result))){
					$arr[] = $res;
				}
				$this->_result->reset();
				$this->_array = $arr;
				return count($this->_array);
			}else
				return count($this->_array);
	}

	public function FetchRow($result = null){
		if($result != null)
			return $result->fetchArray(SQLITE3_ASSOC);
		else if($this->_result != null)
			return $this->_result->fetchArray(SQLITE3_ASSOC);
		else
			return null;
	}

	public function FetchArray($result = null){
		if($result !== null){
			$arr = array();
			while(false !== ($res = $this->FetchRow($result))){
				$arr[] = $res;
			}
			$result->reset();
			return $arr;
		}else
			if($this->_array === null){
				$arr = array();
				while(false !== ($res = $this->FetchRow($this->_result))){
					$arr[] = $res;
				}
				$this->_result->reset();
				$this->_array = $arr;
				return $this->_array;
			}else
				return $this->_array;
	}

	public function Close(){
		return $this->_link->close();
	}
}